#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

struct data{
	int a;
	int b;
};

int a;
pthread_rwlock_t mt;

void cleanup(void* arg)
{
	printf("cleanup: %s\n", (char*)arg);
}

void* thr_1(void* arg)
{
	int i;
	printf("thr_1 start\n");

	for(i = 0; i < 5; i++)
	{
		pthread_rwlock_wrlock(&mt);
		a++;
		printf("thr1 wrlock: a[%d]\n", a);
		sleep(1);
		pthread_rwlock_unlock(&mt);
	}

	printf("thr_1 end\n");

	return((void*)1);
}

void* thr_2(void *arg)
{

	int i;
	printf("thr_2 start\n");

	for(i = 0; i < 5; i++)
	{
		pthread_rwlock_rdlock(&mt);
		//a++;
		printf("thr2 rdlock: a[%d]\n", a);
		pthread_rwlock_unlock(&mt);
	}

	printf("thr_2 end\n");
	pthread_exit((void*) 2);
}

void* thr_3(void *arg)
{

	int i;
	printf("thr_3 start\n");

	for(i = 0; i < 5; i++)
	{
		pthread_rwlock_rdlock(&mt);
		//a++;
		printf("thr3 rdlock: a[%d]\n", a);
		pthread_rwlock_unlock(&mt);
	}

	printf("thr_3 end\n");
	pthread_exit((void*) 3);
}
int main(int argc, char **argv)
{
	struct data  info;

	pthread_t id2;
	pthread_t id1;
	pthread_t id3;

	void* ret;
	int err;
	
	pthread_rwlock_init(&mt, NULL);

	err = pthread_create(&id1, NULL, thr_1, NULL);
	if(err)
	{
		printf("cannot create thr_1: %s\n", strerror(err));
	}

	err = pthread_create(&id2, NULL, thr_2, &info);
	if(err)
	{
		printf("cannot create thread: %s\n", strerror(err));
	}

	err = pthread_create(&id3, NULL, thr_3, &info);
	if(err)
	{
		printf("cannot create thread: %s\n", strerror(err));
	}
	
	err = pthread_join(id1, &ret);
	if(err)
	{
		printf("cannot join with thr_1: %s\n", strerror(err));
	}
	printf("join, thr_1 exit cod: %d\n", (int)ret);
	

	err = pthread_join(id2, &ret);
	if(err)
	{
		printf("cannot join with thr_2: %s\n", strerror(err));
	}
	printf("join, thr_2 exit cod: %d\n", (int)ret);
	
	err = pthread_join(id3, &ret);
	if(err)
	{
		printf("cannot join with thr_3: %s\n", strerror(err));
	}
	printf("join, thr_3 exit cod: %d\n", (int)ret);
	
	pthread_rwlock_destroy(&mt);

	printf("main end\n");
	return 0;
}

